﻿using System;
using System.Collections;
using System.Data;

namespace CrazyTalk.Common
{
    /// <summary>
    /// 数据格式转换
    /// </summary>
    public class DataUtils
    {
        public static ArrayList DataTableToArrayList(DataTable data)
        {
            return DataTableToArrayList(data, null);
        }
        public static ArrayList DataTableToArrayList(DataTable data, object nullDefaultValue)
        {
            ArrayList array = new ArrayList();
            for (int i = 0; i < data.Rows.Count; i++)
            {
                DataRow row = data.Rows[i];
                Hashtable record = new Hashtable();
                for (int j = 0; j < data.Columns.Count; j++)
                {
                    object cellValue = row[j];
                    if (cellValue is DBNull)
                    {
                        cellValue = nullDefaultValue;
                    }
                    record[data.Columns[j].ColumnName] = cellValue;
                }
                array.Add(record);
            }
            return array;
        }
        /// <summary>
        /// 传入DataTable 返回分页数据，total:总行数 rows:返回的行记录。
        /// </summary>
        /// <param name="dtb"></param>
        /// <param name="index"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public static Hashtable ReturnHashtable(DataTable dtb, int index, int size)
        {
            ArrayList dataAll = DataTableToArrayList(dtb);
            ArrayList data = new ArrayList();
            int start = index * size, end = start + size;
            for (int i = 0, l = dataAll.Count; i < l; i++)
            {
                Hashtable record = (Hashtable)dataAll[i];
                if (record == null) continue;
                if (start <= i && i < end)
                {
                    data.Add(record);
                }
            }
            Hashtable result = new Hashtable();
            result["total"] = dataAll.Count;
            result["rows"] = data;
            return result;
        }

        /// <summary>
        /// 将数据行转换为哈希表的存储方式
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        public static Hashtable DataRowToHashtable(DataRow dr)
        {
            Hashtable result = new Hashtable();
            if (dr == null)
                return result;
            foreach (DataColumn column in dr.Table.Columns)
            {
                object cellValue = dr[column.ColumnName];
                if (cellValue is DBNull)
                {
                    cellValue = "";
                }
                result.Add(column.ColumnName, cellValue);
            }
            return result;
        }
    }
}
